package com.ymy.sample.Controller;

import com.ymy.sample.Entity.UsersEntity;
import com.ymy.sample.Service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ymy.hadoop
 * @date 2019/3/19 上午11:24
 */
@RestController
@RequestMapping("users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    /***
     * 获取表中的所有信息
     * @return
     */
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public List<UsersEntity> list(){
        return usersService.usersList();
    }

    /***
     * 通过name来查询信息
     * @param name
     * @return
     */
    @RequestMapping(value = "{name}",method = RequestMethod.GET)
    public UsersEntity findUserOne(@PathVariable("name") String name){
       return usersService.findUserOne(name);
    }

    /***
     * 向表中插入一条数据
     * @param usersEntity
     * @return
     */
    @RequestMapping(value = "save",method = RequestMethod.POST)
    public Map<String,Boolean> save(UsersEntity usersEntity){
        Map<String,Boolean> map = new HashMap<>();
        try {
            usersService.saveUser(usersEntity);
            map.put("status",true);
        }catch (Exception e){
            e.printStackTrace();
            map.put("status",false);
        }
        return map;
    }

    /***
     * 更新表中数据
     * @param usersEntity
     * @return
     */
    @RequestMapping(value = "update",method = RequestMethod.PUT)
    public Map<String,Boolean> update(UsersEntity usersEntity){
        Map<String,Boolean> map = new HashMap<>();
        try {
            usersService.updateUser(usersEntity);
            map.put("status",true);
        }catch (Exception e){
            e.printStackTrace();
            map.put("status",false);
        }
        return map;
    }

    /***
     * 移除表中数据
     * @param name
     * @return
     */
    @RequestMapping(value = "remove",method = RequestMethod.DELETE)
    public Map<String,Boolean> remove(@RequestParam(value = "userName",required = true) String name) {
        Map<String,Boolean> map = new HashMap<>();
        try {
            usersService.removeUser(name);
            map.put("status",true);
        }catch (Exception e){
            e.printStackTrace();
            map.put("status",false);
        }
        return map;
    }

}
